//
//  DetailViewController.swift
//  1604_LimitFree
//
//  Created by 千锋 on 16/9/27.
//  Copyright © 2016年 Mabin. All rights reserved.
//

import UIKit
import CoreLocation

class DetailViewController: LFNavViewController {

    //应用的ID值
    var appId : String?
    
    
    @IBOutlet weak var appImageView: UIImageView!
    
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var lastPriceLabel: UILabel!
    
    @IBOutlet weak var statusLabel: UILabel!
    
    @IBOutlet weak var sizeLabel: UILabel!
    
    @IBOutlet weak var categoryLabel: UILabel!
    
    @IBOutlet weak var rateLabel: UILabel!
    
    
    @IBOutlet weak var sharButton: UIButton!
    

    @IBOutlet weak var favoritreButton: UIButton!
    
    
    @IBOutlet weak var downloadButton: UIButton!
    
    @IBOutlet weak var appScrollView: UIScrollView!
    
    @IBOutlet weak var descLabel: UILabel!
    
    
    @IBOutlet weak var nearByScrollView: UIScrollView!
    
    //详情的数据
    private var detailModel : DetailModel?
    
    //位置管理者
    private var manager : CLLocationManager?
    
    //下载详情是否成功
    private var detailSuccess : Bool?
    
    //下载附近是否成功
    private var nearbySuccess : Bool?

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.darkGrayColor()
        ProgressHUD.showOnView(view)
        
        //下载详情的数据
        downloadDetailData()
        
        //定位
        locate()


    }
    
    //导航
    override func createMyNav() {
        addnavTitle("应用详情")
        
        //返回按钮
       addBackButton()
        
    }
    
    //定位
    func locate()
    {
        manager = CLLocationManager()
        
        
        manager?.distanceFilter = 10
        manager?.desiredAccuracy = kCLLocationAccuracyBest
        
        //请求定位
       
    
        
        if (manager?.respondsToSelector("requestAlwaysAuthorization") == true)
        {
            self.manager?.requestAlwaysAuthorization()
        }
        manager?.delegate = self
        manager?.startUpdatingLocation()

    }

    //显示详情的数据
    func showDetail()
    {
        //1.图片
        let url = NSURL(string: (detailModel?.iconUrl)!)
        appImageView.kf_setImageWithURL(url!)
        //2.名字
        nameLabel.text = detailModel?.name
        //3.原价
        lastPriceLabel.text = "原价￥: "+(detailModel?.lastPrice)!
        //4.状态
        if detailModel?.priceTrend == "limited"
        {
             statusLabel.text = "限免中"
        }
        else if detailModel?.priceTrend == "sales"
        {
            statusLabel.text = "降价中"
        }
        else if detailModel?.priceTrend == "free"
        {
            statusLabel.text = "免费中"
        }
        //5.大小
        sizeLabel.text = (detailModel?.fileSize)!+"MB"
        //6.类型
        categoryLabel.text = MyUtil.transferCateName((detailModel?.categoryName)!)
        //7.评分
        rateLabel.text = "评分: "+(detailModel?.starCurrent)!
        
        //8.App截图
        let count = detailModel?.photos?.count
        
        
        let imageH = 80 //图片的高度
        
        let imageW = 80 //图片的宽度
        
        let marginX = 10 //图片的横向间距

        for i in 0..<count!
        {
            let frame = CGRectMake(CGFloat(imageW+marginX)*CGFloat(i), 0, CGFloat(imageW), CGFloat(imageH))
            let imageView = UIImageView(frame: frame)
            //图片
            let photoModel = detailModel?.photos![i]
            let url = NSURL(string: (photoModel?.smallUrl)!)
            imageView.kf_setImageWithURL(url!)
            
            //添加手势
            
            let g = UITapGestureRecognizer(target: self, action: "tapImage:")
            imageView.userInteractionEnabled = true
            imageView.addGestureRecognizer(g)
            imageView.tag = 1000  + i
            
            
            appScrollView.addSubview(imageView)
        }
       //设置滚动范围
        appScrollView.contentSize = CGSizeMake(CGFloat(imageW+marginX)*CGFloat(count!), 0)
        
        //8.描述
        descLabel.text = detailModel?.desc
    }
    
    //手势响应方法
    func tapImage(g : UIGestureRecognizer)
    {
        let index = (g.view?.tag)! - 1000
        //跳转到图片列表界面
        let photoVC = PhotoViewController()
        photoVC.modalTransitionStyle = .FlipHorizontal
        //点击图片的序号
        photoVC.photoindex = index
        //所有图片的数据
        photoVC.photoArray = detailModel?.photos
        
        
        self.presentViewController(photoVC, animated: true, completion: nil)
    }
    
    
    
    //下载详情的数据
    func downloadDetailData()
    {
        let urlString = String(format: kDetailUrl,appId!)
        let lf = LFDownloader()
        lf.delegate = self
        lf.type = .Detail
        lf.downloadWithURLString(urlString)
    }
    
    
    //详情的解析
    func parseDetailData(data : NSData)
    {
        
//        let str = NSString(data: data, encoding: NSUTF8StringEncoding)
//            print(str!)
        let result = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
        if result.isKindOfClass(NSDictionary)
        {
            let dict = result as! Dictionary<String,AnyObject>
            detailModel = DetailModel()
            detailModel?.setValuesForKeysWithDictionary(dict)
            //将photos里面的字典转换成对象
            var photoArray = Array<PhotoModel>()
            for photoDict in (dict["photos"] as! NSArray)
            {
                //字典转模型
                let model = PhotoModel()
                model.setValuesForKeysWithDictionary(photoDict as! [String : AnyObject])
                photoArray.append(model)
            }
            detailModel?.photos = photoArray
        }
        
        //回到主线程修改界面
        dispatch_async(dispatch_get_main_queue()) {
            
            self.showDetail()
        }
        
    }
    
    //显示附近的数据
    func showNearData(array : Array<LimitModel>)
    {
        let btnW = 60
        let btnh = 80
        let marginX : CGFloat = 10
        
        for i in 0..<array.count
        {
            let model = array[i]
            
            let button = NearByButton(frame: CGRectMake((CGFloat(btnW)+marginX)*CGFloat(i), 0, CGFloat(btnW), CGFloat(btnh)))
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
//            /显示数据
            button.model = model
            
            nearByScrollView.addSubview(button)
        }
        nearByScrollView.contentSize = CGSizeMake((CGFloat(btnW)+marginX)*CGFloat(array.count), 0)
    }
    
    
    func buttonClick(button : NearByButton)
    {
        let detailVC = DetailViewController()
        detailVC.appId = button.model?.applicationId
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    //附近应用的解析
    func parseNearByData(data:NSData)
    {
//        let string = NSString(data: data, encoding: NSUTF8StringEncoding)
//        print(string)
        
        let resule = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        if resule.isKindOfClass(NSDictionary)
        {
            let dict = resule as!Dictionary<String,AnyObject>
            
            var modelArray = Array<LimitModel>()
            let array = dict["applications"] as! Array<Dictionary<String,AnyObject>>
            for appDict in array
            {
                //字典转模型
                let model = LimitModel()
                model.setValuesForKeysWithDictionary(appDict)
                modelArray.append(model)
            }
            dispatch_async(dispatch_get_main_queue(), {
                
                self.showNearData(modelArray)
            })
        }

    }
    
    @IBAction func sharButtonClick(sender: AnyObject) {
    }
    
    @IBAction func favoriteButtonClick(sender: AnyObject) {
        
        
        
    }
    

    @IBAction func downloadButtonClick(sender: AnyObject) {
    }
}






//MARK:LFDownloader代理方法
extension DetailViewController : LFDownloaderDelegate
{
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
        if downloader.type == .Detail
        {
            detailSuccess = false
        }
        else if downloader.type == .NearBy
        {
            nearbySuccess = false
        }
        if detailSuccess == false && nearbySuccess == false
        {
            dispatch_async(dispatch_get_main_queue(), {
                
                ProgressHUD.hideAfterFailOnView(self.view)
            })
        }
    }
    
    func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        
        if downloader.type == .Detail
        {
            self.parseDetailData(data)
            detailSuccess = true
        }
        else if downloader.type == .NearBy
        {
            self.parseNearByData(data)
            nearbySuccess = true
        }
        
        if detailSuccess == false && nearbySuccess == false
        {
            
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), {
                
                ProgressHUD.hideAfterSuccessOnView(self.view)
            })
        }
        
      }
}


extension DetailViewController : CLLocationManagerDelegate
{
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let loc = locations.last
        //如果经纬度有值，就可以获取附近的数据
        if loc?.coordinate.latitude != nil && loc?.coordinate.longitude != nil
        {
            //请求附近的数据
            let urlString = String(format: kNearByUrl,(loc?.coordinate.longitude)!,(loc?.coordinate.latitude)!)
            let downloader = LFDownloader()
            downloader.delegate = self
            downloader.type = .NearBy
            downloader.downloadWithURLString(urlString)
            manager.stopUpdatingLocation()
        }
    }
}

